import { config, more_info, warn_info, more_info_gre } from '@/assets';
import { connect } from 'umi';
import configGre from '@/assets/config_gre.svg';
import { PowerStrategyType } from '@/pages/Tianji/DayRollingTradeStrategy/constant.js';
import { TjIcon } from '@/tjComponents/TjIcon';
import { tableLocale } from '@/tool/components/PageEmpty';
import { NumberSub } from '@/utils';
import { Dropdown, InputNumber, Menu, Message, Radio, Table, Tooltip } from 'antd';
import React, { useEffect, useState } from 'react';
import BenefitSettingModal from '../../modal/BenefitSettingModal';
import ForecastConflictModal from '../../modal/ForecastConflictModal';
import PowerForecastModal from '../../modal/PowerForecastModal';
import PowerSettingModal from '../../modal/PowerSettingModal';
import PriceForecastModal from '../../modal/PriceForecastModal';
import PriceSettingModal from '../../modal/PriceSettingModal';
import styles from './index.less';
import { TRDefault } from '@/components/index.js';
import { TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import {
  getDealPriceInfo,
  getTransactionPowerByVersion,
} from '@/pages/Tianji/DayRollingTradeStrategy/services';

const { Column, ColumnGroup } = Table;

const TableShow = ({
  hourOrderList,
  selectedRowKeys,
  tradeSeqId,
  stationId,
  strategyPowerType,
  forceConflict,
  priceConflict,
  capacity,
  echartsHourOrder,
  strategyId,
  searchStationId,
  tableLimitPower,
  forecastPowerV,
  forecastPriceV,
  historyQuantityV,
  historyQuantityList,
  transactionPowerV,
  transactionPowerList,
  transactionPriceType,
  forecastDate,
  versionData,
  dispatch,
}) => {
  // const [containerHeight, setContainerHeight] = useState(0);
  const powerForecastModalRef = React.useRef();
  const priceForecastModalRef = React.useRef();
  const powerSettingModalRef = React.useRef();
  const priceSettingModalRef = React.useRef();
  const benefitSettingModalRef = React.useRef();
  const forecastConflictModal = React.useRef();
  const tableShowRef = React.useRef();
  const [selectedKey, setSelectedKey] = useState();
  const [selectedKey2, setSelectedKey2] = useState();
  const [selectedTradeElectricity, setSelectedTradeElectricity] = useState();
  const [selectedTradePrice, setSelectedTradePrice] = useState();
  const [historyQuantityListState, setHistoryQuantityListState] = useState([]);
  const [transactionPowerListState, setTransactionPowerListState] = useState([]);
  const [tabDate, setTabDate] = useState();

  /* useEffect(() => {
    if (tableShowRef.current) {
      setContainerHeight(tableShowRef.current.clientHeight);
    }
  }, []); */

  useEffect(() => {
    if (tableLimitPower) {
      setSelectedKey(tableLimitPower);
    }
    if (historyQuantityList) {
      setHistoryQuantityListState(historyQuantityList);
      setSelectedKey2(historyQuantityV);
    }
    if (transactionPowerList) {
      setTransactionPowerListState(transactionPowerList);
      setSelectedTradeElectricity(transactionPowerV);
    }
    if (transactionPriceType) {
      setSelectedTradePrice(transactionPriceType);
    }
    if (forecastDate) {
      setTabDate(forecastDate);
    }
  }, [
    tableLimitPower,
    historyQuantityList,
    transactionPowerList,
    historyQuantityV,
    transactionPowerV,
    transactionPriceType,
    forecastDate,
  ]);

  /**
   * 当序列id或者交易单元id发生改变时，重新获取策略详情
   */
  React.useEffect(() => {
    if (tradeSeqId && searchStationId) {
      dispatch({
        type: 'dayRollingTradeStragety/fetchDetailEffect',
        payload: {
          stationId: searchStationId,
        },
      });
    }
  }, [tradeSeqId, searchStationId]);

  const limitQuantityMenuItems = (
    <Menu
      selectedKeys={[selectedKey]}
      onClick={({ key }) => {
        setSelectedKey(key);
        limitQuantityOperateHandler({ key });
      }}
    >
      <Menu.Item key="1">固定值</Menu.Item>
      <Menu.Item key="2">调整比例</Menu.Item>
    </Menu>
  );

  const historyQuantityMenuItems = (
    <Menu
      selectedKeys={[selectedKey2]}
      onClick={({ key }) => {
        setSelectedKey2(key);
        historyQuantityOperateHandler({ key });
      }}
      style={historyQuantityListState.length == 0 ? { width: '140px' } : {}}
    >
      {historyQuantityListState.length > 0 ? (
        historyQuantityListState.map((item) => <Menu.Item key={item}>{item}</Menu.Item>)
      ) : (
        <TRDefault className={styles.noValue} type={'emptysm'} message={'暂无数据'} />
      )}
    </Menu>
  );

  const dealQuantityMenuItems = (
    <Menu
      selectedKeys={[selectedTradeElectricity]}
      onClick={({ key }) => {
        setSelectedTradeElectricity(key);
        transactionPowerOperateHandler({ key });
      }}
      style={transactionPowerListState.length == 0 ? { width: '140px' } : {}}
    >
      {transactionPowerListState.length > 0 ? (
        transactionPowerListState.map((item) => <Menu.Item key={item}>{item}</Menu.Item>)
      ) : (
        <TRDefault className={styles.noValue} type={'emptysm'} message={'暂无数据'} />
      )}
    </Menu>
  );

  const dealPriceMenuItems = (
    <Menu
      selectedKeys={[selectedTradePrice]}
      onClick={({ key }) => {
        setSelectedTradePrice(key);
        transactionPriceOperateHandler({ key });
      }}
    >
      <Menu.Item key="1">加权价</Menu.Item>
      <Menu.Item key="2">最高价</Menu.Item>
      <Menu.Item key="3">最低价</Menu.Item>
      <Menu.Item key="4">中位数价格</Menu.Item>
    </Menu>
  );

  const changeHourOrderList = (timeOrder, type, value) => {
    let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
    const record = hourOrderListNew[timeOrder - 1];
    record[type] = value;

    try {
      let modifiedPower = record.revisedForecastPower;

      // 计算修正预测出力
      if (type === 'limitQuantity') {
        switch (selectedKey) {
          case '1':
            modifiedPower = NumberSub(record.forecastPower - value);
            break;
          case '2':
            modifiedPower = NumberSub(record.forecastPower * (1 - value));
            break;
          default:
            modifiedPower = 0;
        }
        record.revisedForecastPower = modifiedPower;
        dispatch({
          type: 'dayRollingTradeStragety/setHourOrderList',
          payload: hourOrderListNew,
        });
      }

      // 计算预计回收电量
      let recycleQuantity;

      if (modifiedPower > record.stationCapacity * 0.04) {
        recycleQuantity = Math.min(
          record.baseQuantityRation * modifiedPower + record.contractQuantity - modifiedPower * 3,
          record.contractQuantity,
        );
      } else {
        recycleQuantity = Math.min(
          record.baseQuantityRation * modifiedPower +
            record.contractQuantity -
            record.stationCapacity * 0.12,
          record.contractQuantity,
        );
      }

      if (recycleQuantity < 0) {
        record.expectedRecycleQuantity = 0;
      } else {
        record.expectedRecycleQuantity = (NumberSub(recycleQuantity) || 0).toFixed(3);
      }

      // 计算预计回收电费
      if (recycleQuantity < 0 || record.recyclePrice - record.forecastPrice < 0) {
        record.recycleIncome = 0;
      } else {
        const recycleIncome = recycleQuantity * (record.recyclePrice - record.forecastPrice);
        record.recycleIncome = NumberSub(recycleIncome);
      }

      if (type === 'dayQuantity') {
        // 当修改 dayQuantity 时,同步更新交易持仓和剩余仓位
        // 计算交易持仓 = holdAmount + dayQuantity
        const dealInventory = NumberSub(record.holdAmount + value);
        record.dealInventory = dealInventory;

        // 计算剩余仓位 = 修正预测出力 - 交易持仓
        const residueInventory = NumberSub(record.revisedForecastPower - dealInventory);
        record.residueInventory = residueInventory;
      }

      // 计算预计收益
      if (type === 'declareType' || type === 'declareQuantity' || type === 'declarePrice') {
        const anticipatedIncome = calculateModifiedPower(record);
        record.anticipatedIncome = anticipatedIncome;
      }
    } catch (err) {}

    dispatch({
      type: 'dayRollingTradeStragety/setHourOrderList',
      payload: hourOrderListNew,
    });
  };

  const updateTableData = (resData) => {
    let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
    resData.forEach((item) => {
      const { timeOrder, periodDealAmount, price } = item;
      const index = timeOrder - 1;
      if (index >= 0 && index < hourOrderListNew.length) {
        hourOrderListNew[index] = {
          ...hourOrderListNew[index],
          dealQuantity: periodDealAmount || 0,
          dealPrice: price || 0,
        };
      }
    });

    dispatch({
      type: 'dayRollingTradeStragety/setHourOrderList',
      payload: hourOrderListNew,
    });
  };

  const updateTableData2 = (resData) => {
    let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
    resData.forEach((item) => {
      const { timeOrder, forecastPower, forecastPrice } = item;
      const index = timeOrder - 1;
      if (index >= 0 && index < hourOrderListNew.length) {
        hourOrderListNew[index] = {
          ...hourOrderListNew[index],
          historyQuantity: forecastPower || 0,
          historyPrice: forecastPrice || 0,
        };
      }
    });

    dispatch({
      type: 'dayRollingTradeStragety/setHourOrderList',
      payload: hourOrderListNew,
    });
  };

  const limitQuantityOperateHandler = (val) => {
    const oldType = selectedKey;
    const newType = val.key;

    dispatch({
      type: 'dayRollingTradeStragety/setTableLimitPower',
      payload: val.key,
    });

    // first 重新计算整个表格数据
    let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));

    hourOrderListNew.forEach((record) => {
      // 转换限电量值
      if (oldType && newType && oldType !== newType) {
        // 从比例转固定值
        if (oldType === '2' && newType === '1') {
          record.limitQuantity = NumberSub(record.forecastPower * record.limitQuantity);
        }
        // 从固定值转比例
        else if (oldType === '1' && newType === '2') {
          record.limitQuantity = NumberSub(record.limitQuantity / record.forecastPower);
          // 确保比例在 0-1 之间
          record.limitQuantity = Math.max(0, Math.min(1, record.limitQuantity));
        }
      }
      // 计算修正预测出力
      let modifiedPower = 0;
      try {
        switch (newType) {
          case '1': // 固定值模式
            modifiedPower = NumberSub(record.forecastPower - record.limitQuantity);
            break;
          case '2': // 比例模式
            modifiedPower = NumberSub(record.forecastPower * (1 - record.limitQuantity));
            break;
          default:
            modifiedPower = record.forecastPower;
        }
        record.revisedForecastPower = modifiedPower;

        // 计算预计回收电量
        let recycleQuantity;
        if (modifiedPower > record.stationCapacity * 0.04) {
          recycleQuantity = Math.min(
            record.baseQuantityRation * modifiedPower + record.contractQuantity - modifiedPower * 3,
            record.contractQuantity,
          );
        } else {
          recycleQuantity = Math.min(
            record.baseQuantityRation * modifiedPower +
              record.contractQuantity -
              record.stationCapacity * 0.12,
            record.contractQuantity,
          );
        }
        record.expectedRecycleQuantity = NumberSub(recycleQuantity);

        // 更新预计回收电费
        const recycleIncome = recycleQuantity * (record.recyclePrice - record.forecastPrice);
        record.recycleIncome = NumberSub(recycleIncome);

        // 更新剩余仓位
        const dealInventory = NumberSub(record.holdAmount + (record.dayQuantity || 0));
        record.dealInventory = dealInventory;
        record.residueInventory = NumberSub(modifiedPower - dealInventory);
      } catch (err) {}
    });

    // 更新表格数据
    dispatch({
      type: 'dayRollingTradeStragety/setHourOrderList',
      payload: hourOrderListNew,
    });
  };

  const historyQuantityOperateHandler = async (val) => {
    dispatch({
      type: 'dayRollingTradeStragety/setHistoryQuantityV',
      payload: val.key,
    });
    const params = {
      stationId,
      date: tabDate,
      version: val.key,
    };
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await getTransactionPowerByVersion(params);
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      updateTableData2(res.data);
    } else {
      TRMessage.error(res?.message || '获取交易序列失败');
    }
  };

  const transactionPowerOperateHandler = async (val) => {
    dispatch({
      type: 'dayRollingTradeStragety/setTransactionPowerV',
      payload: val.key,
    });
    const params = {
      date: tabDate,
      marketId: 'PHBSX',
      stationId: stationId,
      version: val.key,
      dealPriceType: selectedTradePrice,
    };
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await getDealPriceInfo(params);
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      updateTableData(res.data);
    } else {
      TRMessage.error(res?.message || '获取交易序列失败');
    }
  };

  const transactionPriceOperateHandler = async (val) => {
    dispatch({
      type: 'dayRollingTradeStragety/setTransactionPriceType',
      payload: val.key,
    });
    const params = {
      date: tabDate,
      marketId: 'PHBSX',
      stationId: stationId,
      version: selectedTradeElectricity,
      dealPriceType: val.key,
    };
    dispatch({
      type: 'dayRollingTradeStragety/setAddLoadingNum',
    });
    const res = await getDealPriceInfo(params);
    dispatch({
      type: 'dayRollingTradeStragety/setSubLoadingNum',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      updateTableData(res.data);
    } else {
      TRMessage.error(res?.message || '获取交易序列失败');
    }
  };

  // 预计收益计算函数
  const calculateModifiedPower = (record) => {
    const {
      declareType,
      declareQuantity,
      revisedForecastPower,
      stationCapacity,
      baseQuantityRation,
      contractQuantity,
      recyclePrice,
      forecastPrice,
      declarePrice,
      recycleIncome,
    } = record;

    // 处理声明数量符号
    const getSignedQuantity = (type, quantity) => {
      if (type === '1') return -Math.abs(quantity); // 买入
      if (type === '2') return Math.abs(quantity); // 卖出
      return quantity;
    };

    const newDeclareQuantity = getSignedQuantity(declareType, declareQuantity);

    // 计算回收后处理量
    const calculateRecycleQuantity = () => {
      const baseValue =
        baseQuantityRation * revisedForecastPower + contractQuantity + newDeclareQuantity;
      const maxValue = contractQuantity + newDeclareQuantity;
      const threshold = stationCapacity * 0.04;

      const subtractValue =
        revisedForecastPower > threshold ? revisedForecastPower * 3 : stationCapacity * 0.12;

      return Math.min(baseValue - subtractValue, maxValue);
    };

    const dealAfterRecycleQuantity = calculateRecycleQuantity();
    // 判断逻辑:
    // 1. 回收后处理量为负数,dealAfterRecycleIncome取0
    // 2. 回收参考价小于预测现货电价,dealAfterRecycleIncome取0
    let dealAfterRecycleIncome = 0;
    if (dealAfterRecycleQuantity > 0 && recyclePrice - forecastPrice > 0) {
      dealAfterRecycleIncome = dealAfterRecycleQuantity * (recyclePrice - forecastPrice);
    }

    const anticipatedIncome =
      (declarePrice - forecastPrice) * newDeclareQuantity +
      (recycleIncome - dealAfterRecycleIncome);

    return anticipatedIncome;
    /* const dealAfterRecycleIncome = dealAfterRecycleQuantity * (recyclePrice - forecastPrice);

    const anticipatedIncome =
      (declarePrice - forecastPrice) * declareQuantity + (recycleIncome - dealAfterRecycleIncome);
    return anticipatedIncome; */
  };

  return (
    <div className={styles.tableShow} ref={tableShowRef}>
      <Table
        className={styles.strategyTable}
        locale={tableLocale}
        dataSource={hourOrderList}
        pagination={false}
        bordered={true}
        rowKey="timeOrder"
        scroll={{ x: 1200 }}
      >
        <Column
          align="center"
          title="时点"
          dataIndex="timeOrderStr"
          key="timeOrderStr"
          fixed="left"
          width={100}
          render={(text) => text || 0}
        />
        <ColumnGroup title="预测">
          <Column
            align="center"
            title={
              <div>
                <Tooltip title={`当前预测版本为${forecastPowerV}`}>
                  <span>预测出力</span>
                </Tooltip>
                <TjIcon
                  gre={configGre}
                  dark={config}
                  className={styles.icon}
                  onClick={() => {
                    powerForecastModalRef.current.initHandle(stationId);
                  }}
                />
              </div>
            }
            dataIndex="forecastPower"
            key="forecastPower"
            width={100}
            render={(text) => text.toFixed(3) || 0}
          />
          <Column
            align="center"
            title={
              <div>
                <span>限电量</span>
                <Dropdown
                  overlay={limitQuantityMenuItems}
                  trigger={['click']}
                  placement="bottomLeft"
                  overlayClassName={styles.dropdownOverlay}
                >
                  <TjIcon gre={more_info_gre} dark={more_info} className={styles.icon} />
                </Dropdown>
              </div>
            }
            dataIndex="limitQuantity"
            key="limitQuantity"
            width={100}
            render={(text, record, index) => (
              <InputNumber
                precision={3}
                min={0}
                className={`${styles.input} ${record.strategyPowerComputed ? styles.computed : ''}`}
                value={record.limitQuantity !== null ? record.limitQuantity : 0}
                onBlur={(e) => {
                  let value = e.target.value;
                  if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                  value = +value;
                  value = NumberSub(value);
                  if (selectedKey === '2') {
                    // 调整比例模式: 0-1
                    value = value > 1 ? 1 : value < 0 ? 0 : value;
                  } else {
                    // 固定值模式: 0-forecastPower
                    value =
                      value > record.forecastPower ? record.forecastPower : value < 0 ? 0 : value;
                  }
                  changeHourOrderList(record.timeOrder, 'limitQuantity', value);
                }}
              />
            )}
          />
          <Column
            align="center"
            title={
              <div>
                <span>修正预测出力</span>
              </div>
            }
            dataIndex="revisedForecastPower"
            key="revisedForecastPower"
            width={100}
            render={(text) => text.toFixed(3) || 0}
          />
          <Column
            align="center"
            title={
              <div>
                <span>预计回收电量</span>
              </div>
            }
            dataIndex="expectedRecycleQuantity"
            key="expectedRecycleQuantity"
            width={100}
            render={(text, record) => {
              let modifiedPower;
              if (record.revisedForecastPower > record.stationCapacity * 0.04) {
                modifiedPower = Math.min(
                  record.baseQuantityRation * record.revisedForecastPower +
                    record.contractQuantity -
                    record.revisedForecastPower * 3,
                  record.contractQuantity,
                );
                // return NumberSub(modifiedPower) || 0;
                // 如果计算结果为负数,返回0
                if (modifiedPower < 0) {
                  return '0.000';
                }

                return NumberSub(modifiedPower).toFixed(3) || '0.000';
              } else {
                modifiedPower = Math.min(
                  record.baseQuantityRation * record.revisedForecastPower +
                    record.contractQuantity -
                    record.stationCapacity * 0.12,
                  record.contractQuantity,
                );
                // return NumberSub(modifiedPower) || 0;
                // 如果计算结果为负数,返回0
                if (modifiedPower < 0) {
                  return '0.000';
                }
                return NumberSub(modifiedPower).toFixed(3) || '0.000';
              }
            }}
          />
          <Column
            align="center"
            title={
              <div>
                <Tooltip title={`当前预测版本为${forecastPriceV}`}>
                  <span>预测现货电价</span>
                </Tooltip>
                <TjIcon
                  gre={configGre}
                  dark={config}
                  className={styles.icon}
                  onClick={() => {
                    priceForecastModalRef.current.initHandle(stationId);
                  }}
                />
              </div>
            }
            dataIndex="forecastPrice"
            key="forecastPrice"
            width={120}
            render={(text) => text.toFixed(2) || 0}
          />
          <Column
            align="center"
            title={
              <div>
                <span>回收参考价</span>
              </div>
            }
            dataIndex="recyclePrice"
            key="recyclePrice"
            width={100}
            render={(text) => text.toFixed(2) || 0}
          />
          <Column
            align="center"
            title={
              <div>
                <span>预计回收电费</span>
              </div>
            }
            dataIndex="recycleIncome"
            key="recycleIncome"
            width={100}
            render={(text, record) => {
              // 检查所需数据是否完整
              if (
                record.expectedRecycleQuantity === null || // 预计回收电量
                record.recyclePrice === null || // 回收参考价
                record.forecastPrice === null // 预测现货电价
              ) {
                return 0;
              }
              // 新增判断逻辑:
              // 1. 预计回收电量为负数,返回0
              // 2. 回收参考价小于预测现货电价,返回0
              if (
                record.expectedRecycleQuantity < 0 ||
                record.recyclePrice - record.forecastPrice < 0
              ) {
                return (record.recycleIncome = 0);
              }

              const fee =
                record.expectedRecycleQuantity * (record.recyclePrice - record.forecastPrice);
              return fee.toFixed(2);
              /* const fee =
                record.expectedRecycleQuantity * (record.recyclePrice - record.forecastPrice);
              return fee.toFixed(2) || 0; */
            }}
          />
        </ColumnGroup>
        <ColumnGroup title="交易结果及仓位">
          <Column
            align="center"
            title={
              <div>
                <span>日滚历史成交电量</span>
                <Dropdown
                  overlay={historyQuantityMenuItems}
                  trigger={['click']}
                  placement="bottomLeft"
                  overlayClassName={styles.dropdownOverlay}
                >
                  <TjIcon gre={more_info_gre} dark={more_info} className={styles.icon} />
                </Dropdown>
              </div>
            }
            dataIndex="historyQuantity"
            key="historyQuantity"
            width={140}
            render={(text) => text.toFixed(3) || 0}
          />
          <Column
            align="center"
            title="日滚历史成交价格"
            dataIndex="historyPrice"
            key="historyPrice"
            width={120}
            render={(text) => text.toFixed(2) || 0}
          />
          <Column
            align="center"
            title={
              <div>
                <span>当日成交电量</span>
              </div>
            }
            dataIndex="dayQuantity"
            key="dayQuantity"
            width={120}
            render={(text, record, index) => (
              <InputNumber
                precision={3}
                className={`${styles.input} ${record.strategyPowerComputed ? styles.computed : ''}`}
                value={record.dayQuantity !== null ? record.dayQuantity : 0}
                onBlur={(e) => {
                  let value = e.target.value;
                  if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                  value = +value;
                  value = NumberSub(value);
                  changeHourOrderList(record.timeOrder, 'dayQuantity', value);
                }}
              />
            )}
          />
          <Column
            align="center"
            title={
              <div>
                <span>当日成交电价</span>
              </div>
            }
            dataIndex="dayPrice"
            key="dayPrice"
            width={120}
            render={(text, record, index) => (
              <InputNumber
                precision={2}
                className={`${styles.input} ${record.strategyPowerComputed ? styles.computed : ''}`}
                value={record.dayPrice !== null ? record.dayPrice : 0}
                onBlur={(e) => {
                  let value = e.target.value;
                  if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                  value = +value;
                  value = NumberSub(value, 2);
                  changeHourOrderList(record.timeOrder, 'dayPrice', value);
                }}
              />
            )}
          />
          <Column
            align="center"
            title="剩余仓位"
            dataIndex="residueInventory"
            key="residueInventory"
            width={120}
            render={(text, record) => {
              if (record.revisedForecastPower === null || record.dealInventory === null) {
                return NumberSub(0, 3);
              }
              const fee = NumberSub(record.revisedForecastPower - record.dealInventory);
              return fee.toFixed(3) || NumberSub(0, 3);
            }}
          />
          <Column
            align="center"
            title="交易持仓"
            dataIndex="dealInventory"
            key="dealInventory"
            width={120}
            render={(text, record) => {
              if (record.dayQuantity === null || record.holdAmount === null) {
                return NumberSub(0, 3);
              }
              const fee = NumberSub(record.holdAmount + record.dayQuantity);
              record.dealInventory = fee;
              return fee.toFixed(3) || NumberSub(0, 3);
            }}
          />
        </ColumnGroup>
        {/* <Column
          align="center"
          title="收益模型"
          width={70}
          render={(text, record, index) => (
            <FileSearchOutlined
              className={styles.modelIcon}
              onClick={() => {
                changeHourOrder(record);
              }}
            />
          )}
        /> */}
        <ColumnGroup title="日滚市场行情">
          <Column
            align="center"
            title={
              <div>
                <span>交易电量</span>
                <Dropdown
                  overlay={dealQuantityMenuItems}
                  trigger={['click']}
                  placement="bottomLeft"
                  overlayClassName={styles.dropdownOverlay}
                >
                  <TjIcon gre={more_info_gre} dark={more_info} className={styles.icon} />
                </Dropdown>
              </div>
            }
            dataIndex="dealQuantity"
            key="dealQuantity"
            width={120}
            render={(text) => text.toFixed(3) || 0}
          />
          <Column
            align="center"
            title={
              <div>
                <span>交易价格</span>
                <Dropdown
                  overlay={dealPriceMenuItems}
                  trigger={['click']}
                  placement="bottomLeft"
                  overlayClassName={styles.dropdownOverlay}
                >
                  <TjIcon gre={more_info_gre} dark={more_info} className={styles.icon} />
                </Dropdown>
              </div>
            }
            dataIndex="dealPrice"
            key="dealPrice"
            width={120}
            render={(text) => text.toFixed(2) || 0}
          />
          <Column
            align="center"
            title={
              <div>
                <span>成交加权均价</span>
                <Tooltip title={`该指标为标的日对应市场历史成交结果的加权均价`}>
                  <span>{''}</span>
                  <TjIcon gre={warn_info} dark={warn_info} className={styles.icon} />
                </Tooltip>
              </div>
            }
            dataIndex="dealAvgPrice"
            key="dealAvgPrice"
            width={120}
            render={(text) => NumberSub(text, 2) || 0}
          />
        </ColumnGroup>
        <ColumnGroup title="交易策略">
          <Column
            align="center"
            title="申报方向"
            dataIndex="declareType"
            key="declareType"
            width={146}
            render={(text, record, index) => (
              <Radio.Group
                value={record.declareType || '1'}
                onChange={(e) => {
                  // changeHourOrderList(record.timeOrder, 'declareType', e.target.value);
                  record.declarePrice = 0;
                  record.declareQuantity = 0;
                  record.anticipatedIncome = 0;
                  const newDeclareType = e.target.value;
                  changeHourOrderList(record.timeOrder, 'declareType', newDeclareType);

                  let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
                  const updatedRecord = hourOrderListNew[record.timeOrder - 1];
                  updatedRecord.declareType = newDeclareType;

                  const anticipatedIncome = calculateModifiedPower(updatedRecord);
                  updatedRecord.anticipatedIncome = anticipatedIncome;

                  dispatch({
                    type: 'dayRollingTradeStragety/setHourOrderList',
                    payload: hourOrderListNew,
                  });
                }}
                options={[
                  { label: '卖出', value: '2' },
                  { label: '买入', value: '1' },
                ]}
              />
            )}
          />
          <Column
            align="center"
            title="申报价格"
            dataIndex="declarePrice"
            key="declarePrice"
            width={120}
            // render={(text) => text.toFixed(2) || 0}
            render={(text, record, index) => (
              <InputNumber
                precision={2}
                className={`${styles.input} ${record.strategyPowerComputed ? styles.computed : ''}`}
                value={record.declarePrice !== null ? record.declarePrice : 0}
                onBlur={(e) => {
                  let value = e.target.value;
                  if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                  value = +value;
                  value = NumberSub(value, 2);
                  changeHourOrderList(record.timeOrder, 'declarePrice', value > 0 ? value : 0);
                }}
              />
            )}
          />
          <Column
            align="center"
            title="申报电量"
            dataIndex="declareQuantity"
            key="declareQuantity"
            width={120}
            render={(text, record) => {
              const buyData =
                versionData?.holdType === '2' ? record.dealInventory : record.buyEnergyLimit;
              const sellData =
                versionData?.holdType === '2' ? record.residueInventory : record.sellEnergyLimit;

              if (record.declareType == '1') {
                const data = Math.max(0, Math.min(record.declareQuantity, buyData)).toFixed(3);
                return (
                  <Tooltip title={`可买入量可输入范围为0-${buyData}`}>
                    <InputNumber
                      precision={3}
                      className={`${styles.input} ${
                        record.strategyPowerComputed ? styles.computed : ''
                      }`}
                      value={data !== null ? data : 0}
                      onBlur={(e) => {
                        let value = e.target.value >= buyData ? buyData : e.target.value;
                        if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                        value = +value;
                        value = NumberSub(value, 3);
                        changeHourOrderList(record.timeOrder, 'declareQuantity', value);
                      }}
                    />
                  </Tooltip>
                );
              } else if (record.declareType == '2') {
                const data = Math.max(0, Math.min(record.declareQuantity, sellData)).toFixed(3);
                return (
                  <Tooltip title={`可买入量可输入范围为0-${sellData}`}>
                    <InputNumber
                      precision={3}
                      className={`${styles.input} ${
                        record.strategyPowerComputed ? styles.computed : ''
                      }`}
                      value={data !== null ? data : 0}
                      onBlur={(e) => {
                        let value = e.target.value >= sellData ? sellData : e.target.value;
                        if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                        value = +value;
                        value = NumberSub(value, 3);
                        changeHourOrderList(record.timeOrder, 'declareQuantity', value);
                      }}
                    />
                  </Tooltip>
                );
              } else {
                return (
                  <InputNumber
                    precision={2}
                    className={`${styles.input} ${
                      record.strategyPowerComputed ? styles.computed : ''
                    }`}
                    value={0}
                    onBlur={(e) => {
                      let value = e.target.value;
                      if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                      value = +value;
                      value = NumberSub(value, 2);
                      changeHourOrderList(record.timeOrder, 'declareQuantity', value);
                    }}
                  />
                );
              }
            }}
          />
          <Column
            align="center"
            title="预计收益"
            dataIndex="anticipatedIncome"
            key="anticipatedIncome"
            width={120}
            render={(text, record) => {
              return (record.anticipatedIncome || 0).toFixed(2);
              /*  const modifiedPower = calculateModifiedPower(record);
              record.anticipatedIncome = modifiedPower;
              return (modifiedPower || 0) .toFixed(2) || 0; */
            }}
          />

          {/* <Column
            align="center"
            title={
              <div>
                <span>交易价格</span>
                <TjIcon
                  gre={configGre}
                  dark={config}
                  className={styles.icon}
                  onClick={() => {
                    priceSettingModalRef.current.initHandle();
                  }}
                />
              </div>
            }
            dataIndex="strategyPrice"
            key="strategyPrice"
            width={85}
            render={(text, record, index) => (
               <InputNumber
                precision={3}
                className={`${styles.input} ${record.strategyPowerComputed ? styles.computed : ''}`}
                value={record.strategyPower !== null ? record.strategyPower : 0}
                onBlur={(e) => {
                  let value = e.target.value;
                  if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                  ///**
                    目标仓位
                    最大值：装机容量 和 已有持仓量+卖出限额 两者中的较小值
                    最小值：0 和 已有持仓量-买入限额 两者中的较大值
                    交易量=目标仓位-已有持仓量
                  // 
                  value = +value;
                  let targetMax = Math.min(capacity, record.holdings + record.sellLimit);
                  let targetMin = Math.max(0, record.holdings - record.buyLimit);
                  let max =
                    strategyPowerType === PowerStrategyType.TARGET_POSITION
                      ? targetMax
                      : targetMax - record.holdings;
                  let min =
                    strategyPowerType === PowerStrategyType.TARGET_POSITION
                      ? targetMin
                      : targetMin - record.holdings;
                  if (value > max) {
                    value = max;
                  } else if (value < min) {
                    value = min;
                  }
                  value = NumberSub(value);
                  changeHourOrderList(record.timeOrder, 'strategyPower', value);
                }}
              />
            )}
          /> */}
        </ColumnGroup>
      </Table>

      <PowerForecastModal ref={powerForecastModalRef} />
      <PriceForecastModal ref={priceForecastModalRef} />
      <PowerSettingModal ref={powerSettingModalRef} />
      <PriceSettingModal ref={priceSettingModalRef} />
      <BenefitSettingModal ref={benefitSettingModalRef} />
      <ForecastConflictModal ref={forecastConflictModal} />
    </div>
  );
};

export default connect(({ dayRollingTradeStragety }) => ({
  hourOrderList: dayRollingTradeStragety.hourOrderList,
  selectedRowKeys: dayRollingTradeStragety.selectedRowKeys,
  tradeSeqId: dayRollingTradeStragety.tradeSeqId,
  stationId: dayRollingTradeStragety.stationId,
  strategyPowerType: dayRollingTradeStragety.strategyPowerType,
  forceConflict: dayRollingTradeStragety.forceConflict,
  priceConflict: dayRollingTradeStragety.priceConflict,
  capacity: dayRollingTradeStragety.capacity,
  echartsHourOrder: dayRollingTradeStragety.echartsHourOrder,
  strategyId: dayRollingTradeStragety.strategyId,
  searchStationId: dayRollingTradeStragety.searchStationId,
  tableLimitPower: dayRollingTradeStragety.tableLimitPower,
  forecastPowerV: dayRollingTradeStragety.forecastPowerV,
  forecastPriceV: dayRollingTradeStragety.forecastPriceV,
  historyQuantityV: dayRollingTradeStragety.historyQuantityV,
  historyQuantityList: dayRollingTradeStragety.historyQuantityList,
  transactionPowerV: dayRollingTradeStragety.transactionPowerV,
  transactionPowerList: dayRollingTradeStragety.transactionPowerList,
  transactionPriceType: dayRollingTradeStragety.transactionPriceType,
  forecastDate: dayRollingTradeStragety.forecastDate,
  versionData: dayRollingTradeStragety.newVersionData,
}))(TableShow);
